package com.yungu.swift.common.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.mapper.IMapper;
import com.yungu.swift.base.service.impl.BaseServiceImpl;
import com.yungu.swift.common.dao.CommonVersionMapper;
import com.yungu.swift.common.model.dto.CommonVersionDto;
import com.yungu.swift.common.model.enums.CommonErrorEnum;
import com.yungu.swift.common.model.param.AdminIosVersionParam;
import com.yungu.swift.common.model.vo.AppVersionVo;
import com.yungu.swift.common.service.CommonVersionService;
import com.yungu.swift.common.util.AppVersionUtils;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.constants.MagicConstant;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright © 厦门云谷互联信息科技有限公司 2018-2020 All Right Reserved
 * <p>
 * 版本信息业务逻辑接口实现类
 *
 * @author Zerrion
 * @version 1.1.0-SNAPSHOT
 * @since 2018-07-05 11:28
 */
@Service
public class CommonVersionServiceImpl extends BaseServiceImpl<CommonVersionDto> implements CommonVersionService {
    /**
     * 版本平台
     **/
    private final static String APP_PLATFORM_IOS = "ios";

    /**
     * 是否强制升级：0.否，1.是
     */
    private final static Integer FORCE_UPGRADE_ZERO = 0;
    private final static Integer FORCE_UPGRADE_ONE = 1;

    @Autowired
    private CommonVersionMapper commonVersionMapper;

    @Override
    protected IMapper<CommonVersionDto> getMapper() {
        return commonVersionMapper;
    }

    @Override
    public ResponseData<AppVersionVo> checkVersion(String platform, String versionNo, Integer identify, String appid) {
        boolean update = false;
        boolean forceUpdate = false;
        boolean isCheck = false;

        //查询该版本的状态
        Map<String, Object> map = MapUtils.build();
        map.put("platform", platform);
        map.put("versionNo", versionNo);
        map.put("identify", identify);
        map.put("appid", appid);

        CommonVersionDto currentVersion = new CommonVersionDto();
        List<CommonVersionDto> list = commonVersionMapper.list(map);
        if (list != null && list.size() > 0) {
            currentVersion = list.get(0);
            if (StringUtils.isNotEmpty(currentVersion.getIsReview()) && MagicConstant.STRING_ONE.equals(currentVersion.getIsReview())) {
                isCheck = true;
            }
            if (MagicConstant.INT_ONE == currentVersion.getStatus()) {
                // 当前版本可用
                forceUpdate = true;
            }
        }
        // 检索该平台当前最新可用版
        map.clear();
        map.put("platform", platform);
        map.put("status", CommonConstant.APP_PKG_STATUS_VALID);
        map.put("identify", identify);
        //排除审核的版本
        map.put("isReview", CommonConstant.APP_IS_REVIEW_SUCCESS);
        map.put("appid", appid);
        list = commonVersionMapper.list(map);
        // 如果用户上传版本小于当前版本则需要更新
        if (list != null && list.size() > 0) {
            currentVersion = list.get(0);
            String clientVersion = versionNo;
            String serverVersion = currentVersion.getVersionNo();
            if (FORCE_UPGRADE_ZERO.equals(currentVersion.getForceUpgrade())) {
                forceUpdate = true;
            }
            try {
                update = AppVersionUtils.compareVersion(clientVersion, serverVersion) < 0;
            } catch (Exception e) {
                e.printStackTrace();
                update = false;
            }
        }
        AppVersionVo appVersionVo = AppVersionVo.getInstance(currentVersion);
        appVersionVo.setIsReview(isCheck);
        appVersionVo.setUpdate(update);
        appVersionVo.setForceUpdate(forceUpdate);
        return ResponseData.buildSuccessResponse(appVersionVo);
    }

    @Override
    public ResponseData<Boolean> saveOrUpdate(AdminIosVersionParam iosVersionParam) {
        // 检查该平台最新可用版本
        Map<String, Object> map = new HashMap<>(8);
        map.put("platform", APP_PLATFORM_IOS);
        map.put("status", iosVersionParam.getStatus());
        map.put("identify", iosVersionParam.getIdentify());
        map.put("appid", iosVersionParam.getAppid());
        List<CommonVersionDto> versionDtos = list(map).getData();
        CommonVersionDto commonVersionDto = new CommonVersionDto();
        BeanUtils.copyProperties(iosVersionParam, commonVersionDto);
        // 新增
        if (StringUtils.isEmpty(commonVersionDto.getUuid())) {
            //新增，判断是否有相同状态的版本，有不让新增
            if (CollectionUtils.isNotEmpty(versionDtos)) {
                CommonErrorEnum iosVersionAddError = CommonErrorEnum.IOS_VERSION_ADD_ERROR;
                return ResponseData.buildErrorResponse(iosVersionAddError.getCode(), iosVersionAddError.getMsg());
            }
            commonVersionDto.setUuid(StringUtils.buildUUID());
            commonVersionDto.setIsReview(CommonConstant.APP_IS_REVIEW_SUCCESS);
            commonVersionDto.setCreateBy(iosVersionParam.getUserUuid());
            commonVersionDto.setPlatform(APP_PLATFORM_IOS);
            commonVersionDto.setAppid(iosVersionParam.getAppid());
            return add(commonVersionDto);
        }
        // 更新
        if (StringUtils.isNotEmpty(commonVersionDto.getUuid())) {
            //如果已经有相同状态为版本，则更新失败
            if (CollectionUtils.isNotEmpty(versionDtos)) {
                CommonVersionDto versionDto = versionDtos.get(0);
                if (!commonVersionDto.getUuid().equals(versionDto.getUuid()) && commonVersionDto.getStatus().equals(
                        versionDto.getStatus())) {
                    CommonErrorEnum iosVersionUpdateError = CommonErrorEnum.IOS_VERSION_UPDATE_ERROR;
                    return ResponseData.buildErrorResponse(iosVersionUpdateError.getCode(), iosVersionUpdateError.getMsg());
                }
            }
            return edit(commonVersionDto);
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "服务器异常");
    }
}